package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.google.common.collect.Lists;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtConfigProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
public class CustomerLoginServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private WeChatService weChatService;
    @Autowired
    private JwtConfigProperties jwtConfigProperties;

    static ArrayList DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //1.调用微信接口获取openid
        String openId = weChatService.getOpenId(dto.getCode());
        //2.根据openid查询  member 查询客户信息
        Member member = memberMapper.selectByOpenId(openId);
        //3.如果客户信息不存在  则创建客户对象 并设置openid
        if (member == null) {
            member =new Member();
            member.setOpenId(openId);
        }
        //4.根据detail.code调用微信接口获取手机号
        String phone = weChatService.getPhone(dto.getPhoneCode());
        //5.新增或者修改用户信息
        saveOrUpdate(member, phone);
        //6.生成jwt令牌（用户id和昵称）
        Map<String,Object> map=new HashMap<>();
        map.put(Constants.JWT_USERID,member.getId());
        map.put(Constants.JWT_USERNAME,member.getName());
        String jwt = JwtUtil.createJWT(jwtConfigProperties.getBase64EncodedSecretKey(), jwtConfigProperties.getTtl(), map);

        //7.返回
        LoginVo loginVo=new LoginVo();
        loginVo.setToken(jwt);
        loginVo.setNickName(member.getName());
        return loginVo;
    }

    private void saveOrUpdate(Member member, String phone) {
        //手机号不一致则更新手机号
        if (!phone.equals(member.getPhone())) {
            member.setPhone(phone);
        }

        if (member.getId() != null) {
            //走修改逻辑
            memberMapper.update(member);
            return;
        }
        //走新增逻辑
        //随机组装昵称，词组+手机号后四位
        String nickName = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
                + StringUtils.substring(member.getPhone(), 7);
        member.setName(nickName);
        memberMapper.insert(member);
    }
}
